﻿$import( "SmitearWebGL.Core.DataPool" );

SmitearWebGL.Core.ResourcePool = SmitearWebGL.Core.DataPool.extend(
{
	/******** constructor ********/

	init : function( context, growSize )
	{
		this._super( growSize || 16 );
		this._registClass( "SmitearWebGL.Core.ResourcePool" );

		/******** private property ********/

		this._resMap = {};
		this._context = context;
	}
	,

	/******** public method ********/

	createResource : function( name, cls, params )
	{
		$THROW( ! this._resMap[name] , "资源名称" + name + "已经存在" );

		var handle = this.addMember( new cls() );
		var resource = this.getResourceByHandle( handle );
		resource.name = name;
		resource.context = this._context;
		resource.setResourcePool( this );
		resource.setResourceHandle( handle );
		this._resMap[name] = handle;

		resource.create( params );

		return resource;
	}
	,
	destroyResource : function( handle )
	{
		var resource = this.getMember( handle );
		var refCount = resource.getReferenceCount();

		if ( refCount == 0 )
		{
			delete this._resMap[resource.name];

			this.removeMember( handle );
		}
	}
	,
	destroyAllResources : function()
	{
		destroy();
	}
	,
	getResourceByHandle : function( handle )
	{
		if ( handle == undefined || handle < 0 || handle > this._numRes - 1 )
		{
			$WARNING( "资源句柄超出范围" );
			return null;
		}

		var resource = this.getMember( handle );
		if ( resource ) resource.addRef();

		return resource;
	}
	,
	getResourceByName : function( name )
	{
		if ( name == undefined || name == null || name == "" || this._resMap[name] == undefined )
		{
			return null;
		}

		return this.getResourceByHandle( this._resMap[name] );
	}
}
);
